#include "searchresultdelegate.h"
#include "globalvar.h"
#include "richlinecode.h"

SearchResultDelegate::SearchResultDelegate(QObject *parent):QStyledItemDelegate(parent)
{

}

void SearchResultDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,const QModelIndex &index) const
{
    if (index.data(Qt::WhatsThisRole).canConvert<RichLineCode>())
    {
        RichLineCode lineCode=index.data(Qt::WhatsThisRole).value<RichLineCode>();
        QString fullText=lineCode.text;

        int richStart=lineCode.startPos;
        int richLength=lineCode.length;

        //QStandardItem* item = static_cast<QStandardItem *>(index.internalPointer());

        QStyle *style = option.widget ? option.widget->style() : QApplication::style();
        QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &option);//获得需要画文本的区域

        QFontMetrics metrics = option.fontMetrics;
        int x=textRect.left();
        int y=textRect.top() + metrics.ascent();
        QString firstStr = fullText.mid(0, richStart).replace("\t", "    ");
        painter->drawText(x, y, firstStr);

        x+=metrics.horizontalAdvance(firstStr);
        QFont font = option.font;
        font.setBold(true);
        QString highlightStr=fullText.mid(richStart, richLength).replace("\t", "    ");;
        metrics = QFontMetrics(font);
        int width = metrics.horizontalAdvance(highlightStr);
        QFont oldFont = painter->font();
        QPen oldPen = painter->pen();
        painter->setPen(GlobalVar::defaultStringColor[GlobalVar::colorTheme].name());
        painter->setFont(font);
        QRect rect = textRect;
        rect.setLeft(x);
        rect.setWidth(width);
        if (highlightStr.trimmed().isEmpty())
            painter->fillRect(rect,qApp->palette().color(QPalette::ColorRole::Highlight));
        painter->drawText(x, y, highlightStr);

        metrics = QFontMetrics(font);
        x+=width;
        painter->setFont(oldFont);
        painter->setPen(oldPen);
        QString lastStr = fullText.mid(richStart+richLength, -1).replace("\t", "    ");;
        painter->drawText(x, y, lastStr);
    }
    else
    {
        QStyledItemDelegate::paint(painter, option, index);
    }
}

QSize SearchResultDelegate::sizeHint(const QStyleOptionViewItem &option,const QModelIndex &index) const
{
    // if (index.data().canConvert<StarRating>()) {
    //     StarRating starRating = qvariant_cast<StarRating>(index.data());
    //     return starRating.sizeHint();
    // }
    return QStyledItemDelegate::sizeHint(option, index);
}
